//
//  UIImage+UIImage.m
//  AFNetworking
//
//  Created by 张xin-鑫 on 2019/6/9.
//

#import "UIImage+Extension.h"
#import <QuartzCore/QuartzCore.h>
#import <Accelerate/Accelerate.h>
@implementation UIImage (Extension)
/**
 *根据当前图像，和指定的尺寸，生成圆角图像并且返回
 * 
 */
- (void)cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor completed:(void (^)(UIImage *image))completed {
    
        dispatch_async(dispatch_get_global_queue(0,0), ^{
          
            
            // 1.利用绘图，建立上下文
            UIGraphicsBeginImageContextWithOptions(size,YES,0);
            
            CGRect rect =CGRectMake(0,0, size.width, size.height);
            
            // 2.设置被裁切的部分的填充颜色
             [fillColor setFill];
            UIRectFill(rect);
            
            // 3.利用贝塞尔路径实现裁切效果
            UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
            
             [path addClip];
            
            // 4.绘制图像
             [self drawInRect:rect];
            
            // 5.取得结果
            UIImage *result =UIGraphicsGetImageFromCurrentImageContext();
            
            // 6.关闭上下文
            UIGraphicsEndImageContext();
            

            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (completed) {
                    
                    completed(result);
                
                }
            
            });
        
        });
    
}
-(UIImage*)rotateImageWithDegree:(CGFloat)degree{

//将image转化成context

//获取图片像素的宽和高
size_t width =self.size.width*self.scale;
size_t height =self.size.height*self.scale;

//颜色通道为8因为0-255经过了8个颜色通道的变化
//每一行图片的字节数因为我们采用的是ARGB/RGBA所以字节数为width * 4
size_t bytesPerRow =width *4;

//图片的透明度通道
CGImageAlphaInfo info =kCGImageAlphaPremultipliedFirst;
//配置context的参数:
CGContextRef context =CGBitmapContextCreate(nil, width, height,8, bytesPerRow,CGColorSpaceCreateDeviceRGB(),kCGBitmapByteOrderDefault|info);

if(!context) {
return nil;
}

//将图片渲染到图形上下文中
CGContextDrawImage(context,CGRectMake(0,0, width, height),self.CGImage);

uint8_t* data = (uint8_t*)CGBitmapContextGetData(context);

//旋转欠的数据

vImage_Buffer src = { data,height,width,bytesPerRow};

//旋转后的数据

vImage_Buffer dest= { data,height,width,bytesPerRow};

//背景颜色
Pixel_8888 backColor = {0,0,0,0};

//填充颜色
vImage_Flags flags = kvImageBackgroundColorFill;

//旋转context
vImageRotate_ARGB8888(&src, &dest,nil, degree , backColor, flags);

//将conetxt转换成image

CGImageRef imageRef =CGBitmapContextCreateImage(context);

UIImage* rotateImage =[UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];

return rotateImage;

}

/**
 *  重新绘制图片修改整张图片填充色
 *
 *  @param color 填充色
 *
 *  @return UIImage
 */
- (UIImage *)imageWithColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
- (instancetype)circleImage
{
    // 开启图形上下文
    UIGraphicsBeginImageContext(self.size);
    
    // 获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 矩形框
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    // 添加一个圆
    CGContextAddEllipseInRect(ctx, rect);
    
    // 裁剪(裁剪成刚才添加的图形形状)
    CGContextClip(ctx);
    
    // 往圆上面画一张图片
    [self drawInRect:rect];
    
    // 获得上下文中的图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭图形上下文
    UIGraphicsEndImageContext();
    
    return image;
}

+ (instancetype)circleImageNamed:(NSString *)name
{
    return [[self imageNamed:name] circleImage];
}

+ (UIImage *)resizedImageWithName:(NSString *)name
{
    return [self resizedImageWithName:name left:0.5 top:0.5];
}

+ (UIImage *)resizedImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top
{
    UIImage *image = [self imageNamed:name];
    return [image stretchableImageWithLeftCapWidth:image.size.width * left topCapHeight:image.size.height * top];
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

+ (UIImage *)imageWithColor:(UIColor *)color andImageWidth:(CGFloat)width andImageHeight:(CGFloat)height
{
    CGFloat imageW = width;
    CGFloat imageH = height;
    // 1.开启基于位图的图形上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageW, imageH), NO, 0.0);
    
    // 2.画一个color颜色的矩形框
    [color set];
    UIRectFill(CGRectMake(0, 0, imageW, imageH));
    
    // 3.拿到图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.关闭上下文
    UIGraphicsEndImageContext();
    
    return image;
}

//截取部分图片并生成新图片
+ (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect
{
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
//    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    return newImage;
}

//返回裁剪区域图片,返回裁剪区域大小图片
+ (UIImage *)clipWithImageRect:(CGRect)clipRect clipImage:(UIImage *)clipImage;
{
    UIGraphicsBeginImageContext(clipRect.size);
    
    [clipImage drawInRect:CGRectMake(0,0,clipRect.size.width,clipRect.size.height)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return  newImage;
    
}

// 拼接多图
+ (UIImage *)composeImg:(CGSize)refSize andPictures:(NSArray<UIImage *>*)pics andColums:(NSInteger)cols
{
    CGFloat picW = refSize.width / cols;
    CGFloat picH = picW;
    CGFloat col = 0;
    CGFloat row = 0;
    CGFloat picX = 0;
    CGFloat picY = 0;
    //以1.png的图大小为画布创建上下文
    UIGraphicsBeginImageContext(CGSizeMake(refSize.width, refSize.height));
    for (int i = 0; i < pics.count; i++) {
        row = i / cols;  //行标
        col = i % cols;  //列标
        picX = col * picW; //X 坐标
        picY = row * picH; //Y 坐标
        [pics[i] drawInRect:CGRectMake(picX, picY, picW, picH)];
    }
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImg;
}

+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image{
    
    //1.确定边框宽度
    //2.开启一个上下文
    CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    //3.绘制大圆,显示出来
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [borderColor set];
    [path fill];
    //4.绘制一个小圆,把小圆设置成裁剪区域
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
    [clipPath addClip];
    //5.把图片绘制到上下文当中
    [image drawAtPoint:CGPointMake(borderW, borderW)];
    //6.从上下文当中取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //7.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}


/**
  返回一张不要渲染的图片
 */
+ (UIImage *)imageWithRenderOriginalName:(NSString *)name{
    UIImage *image =  [UIImage imageNamed:name];
    return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

/**
 图片压缩
 
 @param image image
 @param scaleSize 比例
 @return 图片
 */
+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    image = [UIImage imageWithCGImage:image.CGImage scale:1.0 orientation:UIImageOrientationUp];
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

+ (UIImage *)imageForOtherColor:(NSArray<UIColor*>*)colors andFrame:(CGRect)frame{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    NSMutableArray *color=[NSMutableArray new];
    for (UIColor *c in colors) {
        [color addObject:(__bridge id)c.CGColor];
    }
    gradientLayer.colors = color;
    gradientLayer.locations = @[@0, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 1.0);
    gradientLayer.frame = frame;
    UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.opaque, 0);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}
+ (UIImage *)imageForLROtherColor:(NSArray<UIColor*>*)colors andFrame:(CGRect)frame{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    NSMutableArray *color=[NSMutableArray new];
    for (UIColor *c in colors) {
        [color addObject:(__bridge id)c.CGColor];
    }
    gradientLayer.colors = color;
    gradientLayer.locations = @[@0, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 0.0);
    gradientLayer.frame = frame;
    UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.opaque, 0);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}


+ (UIImage *)imageForOtherColor:(NSArray<UIColor*>*)colors andFrame:(CGRect)frame andOtherLayer:(CALayer*)layer andRadius:(NSInteger)radius{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    NSMutableArray *color=[NSMutableArray new];
    for (UIColor *c in colors) {
        [color addObject:(__bridge id)c.CGColor];
    }
    gradientLayer.colors = color;
    gradientLayer.locations = @[@0, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 1.0);
    gradientLayer.frame = frame;
    UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.opaque, 0);
    [gradientLayer addSublayer:layer];
     if (radius) {
           gradientLayer.cornerRadius=frame.size.height*0.5;
           if (radius>1) {
               gradientLayer.cornerRadius=radius;
           }else{
               gradientLayer.cornerRadius=frame.size.height*0.5;
           }
       }
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}
-(CGFloat)getImageHeightWithImage:(UIImage *)image andWidth:(CGFloat)width{
    CGFloat height = 0.0;
    if (image.size.width) {
        height = width/image.size.width*image.size.height;
    }
    return height;
}
-(CGFloat)getImageWidthWithImage:(UIImage *)image andHeight:(CGFloat)height{
    CGFloat width = 0.0;
    if (image.size.height) {
        width = height/image.size.height*image.size.width;
    }
    return width;
}
//将一个CALayer对象绘制到一个UIImage对象上，并返回这个UIImage对象
+ (UIImage*) imageWithUIView:(UIView*) view
{
    CGSize s = view.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
       UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
    return image;
}

+(UIImage *)createQRCodeWithTargetString:(NSString *)targetString logoImage:(UIImage *)logoImage {
    // 1.创建一个二维码滤镜实例
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    
    // 2.给滤镜添加数据
    NSString *targetStr = targetString;
    NSData *targetData = [targetStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [filter setValue:targetData forKey:@"inputMessage"];
    
    // 3.生成二维码
    CIImage *image = [filter outputImage];
    
    // 4.高清处理: size 要大于等于视图显示的尺寸
    UIImage *img = [UIImage createNonInterpolatedUIImageFromCIImage:image size:[UIScreen mainScreen].bounds.size.width];
    
    //5.嵌入LOGO
    //5.1开启图形上下文
    UIGraphicsBeginImageContext(img.size);
    //5.2将二维码的LOGO画入
    [img drawInRect:CGRectMake(0, 0, img.size.width, img.size.height)];
    if (logoImage) {
        UIImage *centerImg = logoImage;
        CGFloat centerW=img.size.width*0.25;
        CGFloat centerH=centerW;
        CGFloat centerX=(img.size.width-centerW)*0.5;
        CGFloat centerY=(img.size.height -centerH)*0.5;
        [centerImg drawInRect:CGRectMake(centerX, centerY, centerW, centerH)];
    }
    
    //5.3获取绘制好的图片
    UIImage *finalImg=UIGraphicsGetImageFromCurrentImageContext();
    //5.4关闭图像上下文
    UIGraphicsEndImageContext();

    //6.生成最终二维码
    return finalImg;
}

+ (UIImage *)createNonInterpolatedUIImageFromCIImage:(CIImage *)image size:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
   
    // 1.创建bitmap
    size_t width = CGRectGetWidth(extent)*scale;
    size_t height = CGRectGetHeight(extent)*scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    //2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
}

@end
